/**
 * org.assess.oa.system.service.impl.TbUserServiceImpl
 */
package org.assess.oa.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.log4j.Logger;
import org.assess.core.bean.node.TreeNode;
import org.assess.core.common.GeneralUtils;
import org.assess.core.common.SecurityUtils;
import org.assess.core.service.BaseServiceImpl;
import org.assess.core.service.ServiceResult;
import org.assess.oa.system.bean.TbUser;
import org.assess.oa.system.bean.TbUserPost;
import org.assess.oa.system.bean.TbUserRole;
import org.assess.oa.system.bean.TbUserScope;
import org.assess.oa.system.dao.TbUserDAO;
import org.assess.oa.system.dao.TbUserPostDAO;
import org.assess.oa.system.dao.TbUserRoleDAO;
import org.assess.oa.system.dao.TbUserScopeDAO;
import org.assess.oa.system.service.TbUserService;

import com.alibaba.fastjson.JSON;

/**
 * @description 用户管理的Service层实现类
 * @author XiaLongxiang
 * @createtime 2012-5-17 下午12:14:56
 */
public class TbUserServiceImpl extends BaseServiceImpl implements TbUserService {
    /** 操作用户表的DAO层对象 */
    private TbUserDAO tbUserDAO;
    
    /** 操作用户岗位关联表的DAO层对象 */
    private TbUserPostDAO tbUserPostDAO;
    
    /** 操作用户角色关联表的DAO层对象 */
    private TbUserRoleDAO tbUserRoleDAO;
    
    /** 操作用户职能范围信息表的DAO层对象 */
    private TbUserScopeDAO tbUserScopeDAO;
    
    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(TbUserServiceImpl.class);
    
    public TbUser queryTbUserByCode(TbUser user) {
        TbUser result = null;
        try {
            result = this.tbUserDAO.queryTbUserByCode(user.getUser_code(), user.getValid_flag());
        }
        catch (Exception ex) {
            logger.error(ex);
        }
        return result;
    }
    
    public String queryTbUserAsString(int page, int rows, TbUser user) {
        String result = "";
        try {
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("valid_flag", user.getValid_flag());
            parameters.put("user_code", user.getUser_code());
            parameters.put("department_name", user.getDepartment_name());
            int totalrecords = this.tbUserDAO.queryTbUserAsInt(parameters);
            List<TbUser> records = this.tbUserDAO.queryTbUserAsList((page - 1) * rows, rows, parameters);
            result = super.toListPageString(page, rows, totalrecords, "getUser_code", records);
        }
        catch (Exception ex) {
            logger.error(ex);
        }
        
        return result;
    }
    
    public List<TbUserPost> queryTbUserPostByUserCodeAsList(TbUser user, boolean include) {
        List<TbUserPost> results = null;
        try {
            if (include) {
                results = this.tbUserPostDAO.queryTbUserPostByUserCodeAsList(user != null ? user.getUser_code() : "");
            }
        }
        catch (Exception ex) {
            results = new ArrayList<TbUserPost>(0);
            logger.error(ex);
        }
        return results;
    }
    
    public List<TbUserRole> queryTbUserRoleByUserCodeAsList(TbUser user, boolean include) {
        List<TbUserRole> results = null;
        try {
            if (include) {
                results = this.tbUserRoleDAO.queryTbUserRoleByUserCodeAsList(user != null ? user.getUser_code() : "");
            }
        }
        catch (Exception ex) {
            results = new ArrayList<TbUserRole>(0);
            logger.error(ex);
        }
        return results;
    }
    
    public String checkTbUser(TbUser user) {
        String result = "";
        try {
            TbUser record = this.tbUserDAO.queryTbUserByCode(user.getUser_code(), "");
            result = super.toCheckExistsString(record != null && StringUtils.isNotEmpty(record.getUser_code()));
        }
        catch (Exception ex) {
            logger.error(ex);
        }
        return result;
    }
    
    public String updateValid(TbUser user) throws Exception {
        String result = "";
        try {
            String[] user_codes = user.getUser_code().split(",");
            user.setModify_time(new Date());
            user.setModify_user(super.getLoginUserCode());
            for (String code : user_codes) {
                user.setUser_code(code);
                this.tbUserDAO.updateTbUserValid(user);
            }
            
            result = super.toResultString(true);
        }
        catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
        return result;
    }
    
    public ServiceResult saveTbUser(TbUser user, String roleString, String postString, String scopeString, boolean edit)
            throws Exception {
        ServiceResult result = ServiceResult.error_unknown;
        try {
            if (StringUtils.isBlank(user.getFreeze_flag())) {
                user.setFreeze_flag("0");
            }
            if (StringUtils.isNotBlank(user.getPassword())) {
                user.setPassword(SecurityUtils.encryptMD5(user.getPassword()));
            }
            
            TbUser record = this.tbUserDAO.queryTbUserByCode(user.getUser_code(), "");
            if (edit) {
                if (record != null) {
                    if (StringUtils.isBlank(user.getPassword())) {
                        user.setPassword(record.getPassword());
                    }
                    
                    user.setModify_time(new Date());
                    user.setModify_user(super.getLoginUserCode());
                    this.tbUserDAO.update(user);
                    result = ServiceResult.save_success;
                }
            }
            else if (record == null) {
                user.setValid_flag("1");
                user.setCreate_time(new Date());
                user.setCreate_user(super.getLoginUserCode());
                
                this.tbUserDAO.insert(user);
                result = ServiceResult.save_success;
            }
            
            // 如果保存用户信息成功，则接下来保存用户岗位关联信息以及用户角色关联信息
            if (result == ServiceResult.save_success) {
                this.tbUserPostDAO.deleteTbUserPostByUserCode(user.getUser_code());
                this.tbUserRoleDAO.deleteTbUserRoleByUserCode(user.getUser_code());
                this.tbUserScopeDAO.deleteTbUserScopeByUserCode(user.getUser_code());
                
                String[] role_ids = roleString != null ? roleString.split(",") : null;
                if (role_ids != null && role_ids.length != 0) {
                    for (String id : role_ids) {
                        TbUserRole ur = new TbUserRole();
                        ur.setUser_role_id(GeneralUtils.getRandomId(32));
                        ur.setUser_code(user.getUser_code());
                        ur.setRole_id(id.trim());
                        this.tbUserRoleDAO.insert(ur);
                    }
                }
                
                String[] post_ids = postString != null ? postString.split(",") : null;
                if (post_ids != null && post_ids.length != 0) {
                    for (String id : post_ids) {
                        TbUserPost up = new TbUserPost();
                        up.setUser_post_id(GeneralUtils.getRandomId(32));
                        up.setUser_code(user.getUser_code());
                        up.setPost_id(id.trim());
                        this.tbUserPostDAO.insert(up);
                    }
                }
                
                List<TreeNode> scope_list = JSON.parseArray(scopeString, TreeNode.class);
                if (scope_list != null && !scope_list.isEmpty()) {
                    for (TreeNode node : scope_list) {
                        TbUserScope us = new TbUserScope();
                        us.setUser_scope_id(GeneralUtils.getRandomId(32));
                        us.setUser_code(user.getUser_code());
                        us.setDepartment_code(node.getId());
                        this.tbUserScopeDAO.insert(us);
                    }
                }
            }
        }
        catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
        return result;
    }
    
    public Object[] login(String username, String password) throws Exception {
        Object[] result = new Object[2];
        try {
            TbUser record = this.tbUserDAO.queryTbUserByCode(username, "1");
            result[0] = ServiceResult.login_error_username_password;
            if (record != null) {
                // 帐号冻结
                if ("1".equals(record.getFreeze_flag())) {
                    result[0] = ServiceResult.login_error_freeze;
                }
                else if (StringUtils.isNotBlank(password)) {
                    String _sp = SecurityUtils.encryptMD5(password);
                    if (_sp != null && StringUtils.equals(_sp, record.getPassword())) {
                        record.setLogin_time(new Date());
                        this.tbUserDAO.updateUserLoginTime(record);
                        result[0] = ServiceResult.login_success;
                        result[1] = record;
                    }
                }
            }
        }
        catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
        return result;
    }
    
    /**
     * 设置操作用户表的DAO层对象
     * @param tbUserDAO
     */
    public void setTbUserDAO(TbUserDAO tbUserDAO) {
        this.tbUserDAO = tbUserDAO;
    }
    
    /**
     * 设置操作用户岗位关联表的DAO层对象
     * @param tbUserPostDAO
     */
    public void setTbUserPostDAO(TbUserPostDAO tbUserPostDAO) {
        this.tbUserPostDAO = tbUserPostDAO;
    }
    
    /**
     * 设置操作用户角色关联表的DAO层对象
     * @param tbUserRoleDAO
     */
    public void setTbUserRoleDAO(TbUserRoleDAO tbUserRoleDAO) {
        this.tbUserRoleDAO = tbUserRoleDAO;
    }
    
    /**
     * 设置操作用户职能范围信息表的DAO层对象
     * @param tbUserScopeDAO
     */
    public void setTbUserScopeDAO(TbUserScopeDAO tbUserScopeDAO) {
        this.tbUserScopeDAO = tbUserScopeDAO;
    }
}
